const express = require('express');
const router = express.Router();
const experimentController = require('../../controllers/experiment.controller');

// 日志中间件 - 记录所有进入此路由器的请求
router.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] 访问实验路由: ${req.method} ${req.originalUrl}`);
    console.log('请求参数:', {
        params: req.params,
        query: req.query,
        body: req.body
    });
    next();
});

// 实验API路由
router.get('/experiments', async (req, res, next) => {
    console.log('获取所有实验数据请求');
    try {
        const experiments = await experimentController.getAllExperiments(req, res);
        res.json(experiments);
    } catch (err) {
        console.error('获取实验数据失败:', err);   
        res.status(500).json({ error: '服务器内部错误' });
    }
});

router.get('/experiments/:id', (req, res, next) => {
    console.log(`获取单个实验数据请求，实验ID: ${req.params.id}`);
    experimentController.getExperimentById(req, res, next);
});

router.get('/experiments/:experimentId/resources/:resourceId/download', 
    (req, res, next) => {
        console.log(`下载资源请求，实验ID: ${req.params.experimentId}, 资源ID: ${req.params.resourceId}`);
        experimentController.downloadResource(req, res, next);
    }
);

// 错误处理中间件 - 记录路由处理中的错误
router.use((err, req, res, next) => {
    console.error(`[${new Date().toISOString()}] 路由错误: ${err.message}`);
    console.error(err.stack);
    res.status(500).json({ error: '服务器内部错误' });
});

module.exports = router;